﻿using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text.Json;
using System.Threading.Tasks;
using Journeo_backend.Models.GPT;


namespace Journeo_backend.Services.Implementations
{
    public class GptService : IGptService
    {
        private readonly string _apiKey;
        private readonly string _url;
        private readonly HttpClient _httpClient;
        private readonly IAttractionService _attractionService;

        public GptService(IConfiguration configuration, HttpClient httpClient, IAttractionService attractionService)
        {
            _apiKey = configuration["Gpt:ApiKey"];
            _url = configuration["Gpt:Url"];
            _httpClient = httpClient;
            _attractionService = attractionService;
        }

        private class GptResponse
        {
            public List<Choice>? Choices { get; set; }
        }

        private class Choice
        {
            public Message? Message { get; set; }
        }

        // 对话发送方法
        private async Task<T> SendGptRequest<T>(BaseChatRequest request)
        {
            // 创建 HttpRequestMessage
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, _url)
            {
                Content = JsonContent.Create(request)
            };

            // 添加 Headers
            httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);

            // 打印请求详细信息
            string requestContent = await httpRequestMessage.Content.ReadAsStringAsync();

            // 发送请求
            var response = await _httpClient.SendAsync(httpRequestMessage);
            response.EnsureSuccessStatusCode();

            // 读取响应
            var result = await response.Content.ReadFromJsonAsync<GptResponse>();
            if (result?.Choices == null || result.Choices.Count == 0)
            {
                throw new Exception("GPT返回了一个空的响应");
            }

            var message = result.Choices[0].Message;
            int i = 0;
            return JsonSerializer.Deserialize<T>(message?.Content);
        }


        // 简单对话方法
        public async Task<Response<SimpleChatResponse>> SimpleChat(SimpleChatRequest request)
        {
            var chatRequest = new BaseChatRequest
            {
                //Model = "gpt-4o",

                Messages = new List<Message>
            {
                new Message { Role = "system", Content = "你是一名精通中国旅游景点的导游，来自Journeo旅游规划app。" },
                new Message { Role = "user", Content = request.UserMessage }
            },
                ResponseFormat = new ResponseFormat
                {
                    Type = "json_schema",
                    JsonSchema = new JsonSchema
                    {
                        Name = "simple_chat_response",
                        Strict = true,
                        Schema = SchemaConstants.SimpleResponse
                    }
                }
            };

            var response = await SendGptRequest<SimpleChatResponse>(chatRequest);

            return new Response<SimpleChatResponse>(response);
        }

        // 旅游推荐方法
        public async Task<Response<TravelRecommendResponse>> GetTravelRecommendations(TravelRecommendRequest request)
        {
            var systemPrompt = $"你是一名精通中国旅游景点的导游，来自Journeo旅游规划app。";
            var userPrompt = "请根据以下信息分析旅游请求并提供推荐，这对我很重要：\n" +
                             $"目的地城市: {request.Destination ?? "未知"}\n" +
                             $"天数: {request.Days?.ToString() ?? "未知"}\n" +
                             $"旅行风格: {request.TravelStyle ?? "未知"}\n" +
                             $"预算: {request.Budget?.ToString() ?? "未知"}\n" +
                             $"偏好: {(request.Preferences ?? "未知")}";

            var chatRequest = new BaseChatRequest
            {
                //Model = "gpt-4o",

                Messages = new List<Message>
            {
                new Message { Role = "system", Content = systemPrompt },
                new Message { Role = "user", Content = userPrompt }
            },
                ResponseFormat = new ResponseFormat
                {
                    JsonSchema = new JsonSchema
                    {
                        Name = "travel_recommendation",
                        Schema = SchemaConstants.TravelRecommendation
                    }
                }
            };

            var response = await SendGptRequest<TravelRecommendResponse>(chatRequest);

            int i = 0;

            return new Response<TravelRecommendResponse>(response);
        }

        // 景点分析方法
        public async Task<Response<SpotAnalysisResponse>> AnalyzeSpots(SpotAnalysisRequest request)
        {
            try
            {
                // 根据SpotId数组获取景点信息列表
                var attractions = await _attractionService.GetAttractions(request.SpotId);

                // 使用大括号分隔景点信息
                var attractionsInfo = string.Join("\n}\n{\n", attractions.Select(a =>
                    $"名称: {a.Name ?? "未知"}, \n"+
                    // 取Description的第一个句号之前的部分
                    $"简介: {a.Description?.Split('。')[0] ?? "未知"}, \n" +
                    $"五分制评分: {a.AttractionRating?.ToString() ?? "未知"},\n" +
                    $"地址: {a.Address ?? "未知"}, \n门票价格: {a.PriceRange?.ToString() ?? "未知"}, \n" +
                    $"开放时间: {a.OpeningHours ?? "未知"}, \n" +
                    $"推荐游览耗时: {a.RecommendedVisitTime?.ToString() ?? "未知"}"
                ));

                // 包裹整个字符串
                attractionsInfo = "{\n" + attractionsInfo + "\n}";

                var systemPrompt = $"你是一名精通中国旅游景点的导游，来自Journeo旅游规划app。";
                var userPrompt = $"请根据以下信息分析景点请求并提供推荐, 分别说明这些景点是否适合本次旅行，是否值得推荐。这对我很重要：\n" +
                                 $"人数: {request.TravelInfo?.NumPeople?.ToString() ?? "未知"}\n" +
                                 $"平均年龄: {request.TravelInfo?.avgAge?.ToString() ?? "未知"}\n" +
                                 $"计划城市: {request.TravelInfo?.Destination ?? "未知"}\n" +
                                 $"计划天数: {request.TravelInfo?.Days?.ToString() ?? "未知"}\n" +
                                 $"计划旅行风格: {request.TravelInfo?.TravelStyle ?? "未知"}\n" +
                                 $"计划预算: {request.TravelInfo?.Budget?.ToString() ?? "未知"}\n" +
                                 $"旅行偏好: {request.TravelInfo?.Preferences ?? "未知"}\n" +
                                 $"待分析景点信息: {attractionsInfo}\n";

                var chatRequest = new BaseChatRequest
                {
                    Messages = new List<Message>
                    {
                        new Message { Role = "system", Content = systemPrompt },
                        new Message { Role = "user", Content = userPrompt }
                    },
                    ResponseFormat = new ResponseFormat
                    {
                        JsonSchema = new JsonSchema
                        {
                            Name = "spot_analysis",
                            Schema = SchemaConstants.SpotAnalysis
                        }
                    }
                };

                var response = await SendGptRequest<SpotAnalysisResponse>(chatRequest);

                return new Response<SpotAnalysisResponse>(response);
            }
            catch (Exception e)
            {
                throw new Exception("景点分析失败", e);
            }
        }

        // 连续对话方法
        public async Task<Response<SimpleChatResponse>> ContinuousChat(ContinuousChatRequest request)
        {
            // 首先确保历史记录中包含系统消息
            if (!request.ChatHistory.Any() || request.ChatHistory[0].Role != "system")
            {
                request.ChatHistory.Insert(0, new Message
                {
                    Role = "system",
                    Content = "你是一名精通中国旅游景点的导游，来自Journeo旅游规划app。"
                });
            }

            // 添加新的用户消息
            request.ChatHistory.Add(new Message
            {
                Role = "user",
                Content = request.NewMessage
            });

            var chatRequest = new BaseChatRequest
            {
                Messages = request.ChatHistory,
                ResponseFormat = new ResponseFormat
                {
                    JsonSchema = new JsonSchema
                    {
                        Name = "continuous_chat_response",
                        Schema = SchemaConstants.SimpleResponse
                    }
                }
            };

            var response = await SendGptRequest<SimpleChatResponse>(chatRequest);
            return new Response<SimpleChatResponse>(response);
        }
    }
}
